package com.lagou.myrpcprovider;

import com.alibaba.fastjson.JSONObject;
import com.lagou.myrpcprovider.server.RpcServer;
import com.lagou.rpc.pojo.Ts;
import com.lagou.rpc.utils.GetZkClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Set;

@SpringBootApplication
public class RpcProviderApplication implements CommandLineRunner {

    @Autowired
    RpcServer rpcServer;

    private String ip = "127.0.0.1";

    private Integer port = 8092;

    public static void main(String[] args) {
        SpringApplication.run(RpcProviderApplication.class, args);
    }


    @Override
    public void run(String... args) throws Exception {
        new Thread(() -> rpcServer.startServer(ip, port)).start();
        //new Thread(() -> rpcServer.startServer("127.0.0.1", 8092)).start();
        // 将服务器注册到Zk上面
        registerZk();
    }


    // 注册服务端信息到zookeeper
    /**
     *  将服务端的信息（ip + port） 注册到zookeeper上
     */
    void registerZk(){
        CuratorFramework zkClient = GetZkClient.getZkClient();
        String path = GetZkClient.path + "/" + ip + ":" + port;
        try {
            Ts ts = new Ts();
            ts.setLatsTime(System.currentTimeMillis());
            String tsStr = JSONObject.toJSONString(ts);

            zkClient.create().creatingParentContainersIfNeeded()
                    // 创建临时顺序节点
                    .withMode(CreateMode.EPHEMERAL)
                    // 存储当前时间，到时候会和当前时间进行对比
                    .forPath(path,tsStr.getBytes());
            watchNode(zkClient);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  监控zookeeper节点的变化 被删除就进行注册
     */
    private  void watchNode(CuratorFramework zkClient) throws Exception {
        TreeCache treeCache = new TreeCache(zkClient, GetZkClient.path);
        treeCache.getListenable().addListener((curatorFramework, treeCacheEvent) -> {

            TreeCacheEvent.Type type = treeCacheEvent.getType();
            // 添加节点暂时不进行任何处理
            if (type == TreeCacheEvent.Type.NODE_ADDED){

            // 如果删除 就继续进行注册
            }else if (type == TreeCacheEvent.Type.NODE_REMOVED){ // 节点删除
                String path = GetZkClient.path + "/" + ip + ":" + port;
                zkClient.create().creatingParentContainersIfNeeded()
                        // 创建临时顺序节点
                        .withMode(CreateMode.EPHEMERAL)
                        // 存储当前时间，到时候会和当前时间进行对比
                        .forPath(path,(String.valueOf(System.currentTimeMillis())).getBytes());
            }
        });
        treeCache.start();
    }


}
